package com.share.factory.strategy;

import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.enums.HttpStatusEnum;
import com.share.common.enums.UserStatusEnum;
import com.share.constant.SecurityConstant;
import com.share.exception.BaseException;
import com.share.properties.GiteeProperties;
import com.share.properties.WeChatProperties;
import com.share.service.ISysUserService;
import com.share.service.OAuthService;
import com.share.service.WebSocketService;
import com.share.user.Gitee.GiteeUserInfo;
import com.share.user.Gitee.ProviderToken;
import com.share.user.admin.dtos.PayloadDTO;
import com.share.user.admin.pojos.SysUser;
import com.share.user.admin.vo.LoginVo;
import com.share.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;

/**
 * Gite登录
 */
@Slf4j
@Service
public class GiteAuthStrategy extends AbstractAuthStategy {
    private final GiteeProperties giteeProperties;
    private final WebSocketService webSocketService;
    private final TokenUtils tokenUtils;
    private final OAuthService oAuthService;
    private final ISysUserService sysUserService;

    @Autowired
    public GiteAuthStrategy(GiteeProperties giteeProperties , WebSocketService webSocketService, TokenUtils tokenUtils, OAuthService oAuthService, ISysUserService sysUserService) {
        this.giteeProperties = giteeProperties;
        this.webSocketService = webSocketService;
        this.tokenUtils = tokenUtils;
        this.oAuthService = oAuthService;
        this.sysUserService = sysUserService;
    }

    @Override
    public void thirdPartyLogin(String code){
        log.info("Gite登录");
        //用户授权信息
        ProviderToken token = new ProviderToken();
        token.setClientId(giteeProperties.getClientId());
        token.setRedirectUri(giteeProperties.getRedirectUri());
        token.setClientSecret(giteeProperties.getClientSecret());
        token.setCode(code);
        //获取token和登录的用户信息
        Map<String,String> giteeToken = oAuthService.getGiteeToken(token);
        log.info("accessToken:{}", giteeToken);
        GiteeUserInfo giteeUser = oAuthService.getGiteeUser(giteeToken.get("access_token"));
        log.info("giteeUser:{}", giteeUser);
        if(giteeUser == null){
            throw new BaseException(HttpStatusEnum.FORBIDDEN,"登录失败", Instant.now());
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getEmail, giteeUser.getEmail());
        SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper);
        if(sysUser == null){
            //创建账号并登录
            sysUser = new SysUser();
            sysUser.setEmail(giteeUser.getEmail());
            sysUser.setNickname(giteeUser.getName());
            sysUser.setUsername("gitee"+ UUID.randomUUID().toString().substring(7));
            sysUser.setStatus(UserStatusEnum.ACTIVE);
            sysUserService.save(sysUser);
        }
        LoginVo loginVo = tokenUtils.LoginInformation(sysUser);
        // 4. 仅发送给该用户（而不是广播）
        webSocketService.sendMessageToClients(JSON.toJSONString(loginVo));
    }
}
